package com.szyportal.web.back.controller.website;

import com.alibaba.fastjson.JSONObject;
import com.szyportal.common.annotation.Log;
import com.szyportal.common.core.controller.BaseController;
import com.szyportal.common.core.domain.AjaxResult;
import com.szyportal.common.core.page.TableDataInfo;
import com.szyportal.common.dto.DeployDTO;
import com.szyportal.common.enums.BusinessType;
import com.szyportal.common.utils.StringUtils;
import com.szyportal.common.utils.poi.ExcelUtil;
import com.szyportal.common.utils.ssh.ScpWithVFS;
import com.szyportal.custom.domain.WAbout;
import com.szyportal.custom.service.IWAboutService;
import com.szyportal.web.back.controller.tool.StaticResourceCopier;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;

/**
 * 关于我们Controller
 * 
 * @author ruoyi
 * @date 2024-12-03
 */
@Controller
@RequestMapping("/back/deploy")
@Slf4j
public class WDeployController extends BaseController
{
    private String prefix = "back/szyportal/deploy";

    @Autowired
    private StaticResourceCopier staticResourceCopier;

    @Value("${ruoyi.profile}")
    private String ruoyiProfile;


    /**
     * 网站部署展示页
     */
    @GetMapping("/show")
    public String show()
    {
        return prefix + "/show";
    }

    /**
     * 网站部署触发器
     */
    @PostMapping("/commit")
    @Log(title = "网站部署触发器", businessType = BusinessType.INSERT)
//    @ResponseBody
    public String commit(DeployDTO deployDTO)
    {
        log.info("===>commit=>deployDTO:{}",deployDTO);
        if(Strings.isEmpty(deployDTO.getDeployPath()) && Strings.isEmpty(deployDTO.getIp())){
            return prefix + "/show";
        }

        if(Strings.isNotEmpty(deployDTO.getDeployPath())){
//            本地部署
            deployLocal(deployDTO);
        }else {
//            远程部署
            deployRemote(deployDTO);
        }

        return prefix + "/show";
    }

    public String deployRemote(DeployDTO deployDTO){
        String ip = deployDTO.getIp();
        String port = deployDTO.getPort();
        String username = deployDTO.getUsername();
        String password = deployDTO.getPassword();
        String remotePath = deployDTO.getRemotePath();
        String tempPath = ruoyiProfile.concat("/").concat(String.valueOf(System.currentTimeMillis()));

        deployDTO.setDeployPath(tempPath);
        deployLocal(deployDTO);

        //tempPath copy to remote linux
        ScpWithVFS scpWithVFS = new ScpWithVFS(ip,port,username,password,tempPath,remotePath);
        boolean start = scpWithVFS.start();
        log.info("===>deployRemote=>start:{}",start);

        //删除tempPath
        try {
            StaticResourceCopier.deleteDirectory(new File(tempPath));
        } catch (IOException e) {
            log.info("===>deployRemote=>e:{}",e.getMessage());
//            e.printStackTrace();
        }

        return prefix + "/show";
    }

    public String deployLocal(DeployDTO deployDTO)
    {
        try {
            //static source
            staticResourceCopier.copyStaticResources(deployDTO.getDeployPath());
            //upload img
            staticResourceCopier.copyStaticResources(ruoyiProfile.concat("/upload"),deployDTO.getDeployPath().concat("/profile/upload"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //path - fileName
        HashMap<String,String> pageMap = new HashMap<>();
        pageMap.put("/","index.html");
        pageMap.put("/about.html","about.html");
        pageMap.put("/service.html","service.html");
        pageMap.put("/case.html?pageSize=9","case.html");
        pageMap.put("/partner.html","partner.html");
        pageMap.put("/news.html","news.html");
        pageMap.put("/contact.html","contact.html");

        String outputDir = deployDTO.getDeployPath();
        String apiUrl = "http://127.0.0.1:8099";
//        String fileName = "/index.html";
        RestTemplate restTemplate = new RestTemplate();

        pageMap.forEach((path,fileName) -> {
            try {
                // 调用API
                ResponseEntity<String> respEntity = restTemplate.getForEntity(apiUrl + path, String.class);
                log.info("===>deployLocal=>response.getHeaders().getContentType():{}",respEntity.getHeaders().getContentType());
                String apiResponse = respEntity.getBody();
                log.info("===>deployLocal=>apiResponse1:{}",apiResponse);

//                // 手动修复编码（如果服务端未正确声明 charset）
                apiResponse = new String(apiResponse.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);

                log.info("===>deployLocal=>apiResponse2:{}",apiResponse);

                // 保存文件
                Path outputPath = Paths.get(outputDir);
                if (!Files.exists(outputPath)) {
                    Files.createDirectories(outputPath);
                }
                Path filePath = outputPath.resolve(fileName);
                Files.write(
                        filePath,
                        apiResponse.getBytes(StandardCharsets.UTF_8)
                );

//                System.out.println("HTML文件已保存到: " + filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return prefix + "/show";
    }

}
